//
//  CustomerDetailsViewController.m
//  QinrenManagers
//
//  Created by easaa on 15/7/20.
//  Copyright (c) 2015年 easaa. All rights reserved.
//

#import "CustomerDetailsViewController.h"

#import "ProgramKindViewController.h"
//下拉框
#import "ComboBoxView.h"

#import "RecordTableViewCell.h"

#import "CustomerRecordModel.h"

#import "ProductListModel.h"

@interface CustomerDetailsViewController ()<UITableViewDataSource,UITableViewDelegate,sendSelectecdIndexDelegate>

{
    ComboBoxView  *_comboBox;
    
    NSInteger _comboxSelectedIndex0;
    NSInteger _comboxSelectedIndex1;
    
    NSInteger _pageIndex0;
   // NSInteger _pageIndex1;
    
    UIView * _headerView;
    
    BOOL _needRefresh0;
//    BOOL _needRefresh1;

    
}

/**解决方案数据源*/
@property (nonatomic, strong) NSMutableArray * schemeDataSource;
/**消费记录数据源*/
@property (nonatomic, strong) NSMutableArray * recordDataSource;

@property (nonatomic, strong) UITableView * baseTableView;

@property (nonatomic, strong) UISegmentedControl * segmentControl;

@end

@implementation CustomerDetailsViewController

- (instancetype)init
{
    self = [super init];
    if (self) {
        _schemeDataSource = [NSMutableArray array];
        _recordDataSource = [NSMutableArray array];

        _comboxSelectedIndex0 = 0;
        _comboxSelectedIndex1 = 0;
        _pageIndex0 = 1;
//        _pageIndex1 = 1;
    
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self requestForData];
    [self requestForRecordData];
    [self creatTableView];
    [self creatHeaderView];

    
}

#pragma mark --------- 网络请求-------------
- (void)requestForData
{
    
    EAHttpAPIClient *manager = [EAHttpAPIClient manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    NSDictionary *parameters = @{@"customer_id":self.customer_id,@"pagesize":@"10",@"pageindex":[NSString stringWithFormat:@"%ld",(long)_pageIndex0],@"time":[NSString stringWithFormat:@"%ld",(long)_comboxSelectedIndex0]};
    NSLog(@"%@",parameters);
    [manager GetWithParameters:parameters method:@"search.solution.list" success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *resposeString ;
        if ([responseObject isKindOfClass:[NSData class]]) {
            resposeString = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        }else
            resposeString = responseObject;
        
        NSString *jsonString = [DataParser parseString:resposeString];
        id dictionary = [JSONKit jsonToArrayOrDictionary:jsonString];
        NSLog(@"客户解决方案的dictonary :%@",[dictionary description]);
        
        
        if ([[dictionary objectForKey:@"verification"]intValue] == 1)
        {
            if (_needRefresh0) {
                [SVProgressHUD showSuccessWithStatus:@"请求数据中"];
                [_schemeDataSource removeAllObjects];
            }
            
            for (NSDictionary *dataDic in dictionary[@"data"]) {
                
                ProductListModel *productListModel = [[ProductListModel alloc]init];
                [productListModel setValuesForKeysWithDictionary:dataDic];
                [_schemeDataSource addObject:productListModel];
            
            }
            
            [_baseTableView reloadData];
            _baseTableView.legendFooter.hidden = NO;
            
            
            if ([dictionary[@"total"] integerValue] < 10) {
                
                //[_personalTableView.footer resetNoMoreData];
                
                [_baseTableView.footer endRefreshing];
                [_baseTableView.header endRefreshing];
                [_baseTableView.footer noticeNoMoreData];
                return ;
            }

            
        }
        else
        {
            
            NSString *error = [dictionary objectForKey:@"error"];
            [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeClear];
            [SVProgressHUD showErrorWithStatus:error];
        }
        
        [_baseTableView.footer endRefreshing];
        [_baseTableView.header endRefreshing];
        [_baseTableView.footer noticeNoMoreData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeClear];
        [SVProgressHUD showErrorWithStatus:[error localizedDescription]];
        [_baseTableView.footer endRefreshing];
        [_baseTableView.header endRefreshing];

    }];
    
}

- (void)requestForRecordData
{
    
    EAHttpAPIClient *manager = [EAHttpAPIClient manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSDictionary *parameters = @{@"uid":self.customer_id,@"time":[NSString stringWithFormat:@"%ld",(long)_comboxSelectedIndex1]};
    NSLog(@"%@",parameters);
    [manager GetWithParameters:parameters method:@"get.user.score" success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *resposeString ;
        if ([responseObject isKindOfClass:[NSData class]]) {
            resposeString = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        }else
            resposeString = responseObject;
        
        NSString *jsonString = [DataParser parseString:resposeString];
        id dictionary = [JSONKit jsonToArrayOrDictionary:jsonString];
        NSLog(@"消费记录的dictonary :%@",[dictionary description]);
        
        
        if ([[dictionary objectForKey:@"verification"]intValue] == 1)
        {
//            if (_needRefresh1) {
//                [SVProgressHUD showSuccessWithStatus:@"请求数据中"];
//                [_recordDataSource removeAllObjects];
//            }
            [_recordDataSource removeAllObjects];
            
            for (NSDictionary *dataDic in dictionary[@"data"]) {
                
                CustomerRecordModel *customerRecordModel = [[CustomerRecordModel alloc]init];
                [customerRecordModel setValuesForKeysWithDictionary:dataDic];
                [_recordDataSource addObject:customerRecordModel];
                
            }
            
            [_baseTableView reloadData];
            _baseTableView.legendFooter.hidden = YES;
            
            
        }
        else
        {
            
            NSString *error = [dictionary objectForKey:@"error"];
            [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeClear];
            [SVProgressHUD showErrorWithStatus:error];
        }
        
        [_baseTableView.footer endRefreshing];
        [_baseTableView.header endRefreshing];
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeClear];
        [SVProgressHUD showErrorWithStatus:[error localizedDescription]];
        [_baseTableView.footer endRefreshing];
        [_baseTableView.header endRefreshing];
        
    }];
    
}


- (void)creatHeaderView
{
    _headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_W, 50)];
    
    _headerView.backgroundColor = Lightlightcolor;
    
    [self.view addSubview:_headerView];
    
    //自定义UISegmentedcontrol
    
    _segmentControl=[[UISegmentedControl alloc] initWithFrame:CGRectMake(5, 5, SCREEN_W * 0.7, 40) ];
    [_segmentControl insertSegmentWithTitle:@"解决方案" atIndex:0 animated:YES];
    [_segmentControl insertSegmentWithTitle:@"消费记录" atIndex:1 animated:YES];
    _segmentControl.selectedSegmentIndex = 0;
    _segmentControl.momentary = NO;
    _segmentControl.multipleTouchEnabled=NO;
    [_segmentControl addTarget:self action:@selector(segmentIndexChanged) forControlEvents:UIControlEventValueChanged];
    
    [_headerView addSubview:_segmentControl];
    
    [self creatComboBox];
}

- (void)creatComboBox
{
    NSArray *comboBoxDatasource = [[NSArray alloc] initWithObjects:@"全部", @"本周", @"本月", @"最近三月", @"最近半年", @"最近一年", nil];
    
    _comboBox = [[ComboBoxView alloc] initWithFrame:CGRectMake(SCREEN_W - SCREEN_W/4-5, 72, SCREEN_W/4, 200)];
    _comboBox.comboBoxDatasource = comboBoxDatasource;
    _comboBox.backgroundColor = [UIColor clearColor];
    _comboBox.delegate = self;
    [_comboBox setContent:[comboBoxDatasource objectAtIndex:0]];
   
    [self.view addSubview:_comboBox];
}

- (void)creatTableView
{
    _baseTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 44, SCREEN_W, SCREEN_H-50) style:UITableViewStylePlain];
    
    _baseTableView.delegate = self;
    _baseTableView.dataSource = self;
    
    _baseTableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    [self.view addSubview:_baseTableView];
    
    
    UINib * nib1 = [UINib nibWithNibName:@"RecordTableViewCell" bundle:nil];
    
    [_baseTableView registerNib:nib1 forCellReuseIdentifier:@"recordCell"];
    
    __weak typeof(self) weakSelf = self;
    [_baseTableView addLegendHeaderWithRefreshingBlock:^{
        [weakSelf headerRefresh];
    }];
    [_baseTableView addLegendFooterWithRefreshingBlock:^{
        [weakSelf footerRefresh];
    }];
    
    
}
- (void)headerRefresh{
    
    if (_segmentControl.selectedSegmentIndex == 0) {
        _needRefresh0 = YES;
        _pageIndex0 = 1;
        [self requestForData];
    }
    else if (_segmentControl.selectedSegmentIndex == 1) {
//        _needRefresh1 = YES;
//        _pageIndex1 = 1;
        [self requestForRecordData];
    }

}
- (void)footerRefresh{
    
    
    if (_segmentControl.selectedSegmentIndex == 0) {
        _needRefresh0 = NO;
        _pageIndex0 ++;
        [self requestForData];
    }
//    else if (_segmentControl.selectedSegmentIndex == 1) {
//        _needRefresh1 = NO;
//        _pageIndex1 ++;
//        [self requestForData];
//    }

}


#pragma mark - buttonClickEvent

- (void)segmentIndexChanged
{
    switch (_segmentControl.selectedSegmentIndex) {
        case 0:
            
            NSLog(@"解决方案");
            [_baseTableView reloadData];
            break;
        case 1:
        {
            
            NSLog(@"消费记录");
            
            [_baseTableView reloadData];
            
        }
            break;
        default:
            break;
    }
}

#pragma mark-sendSelectecdIndexDelegate
- (void)sendSelectedIndex:(NSInteger)selectedIndex{
    
    if (_segmentControl.selectedSegmentIndex == 0) {
        [_schemeDataSource removeAllObjects];
        _comboxSelectedIndex0 = selectedIndex;
        [self requestForData];

    }
    else if (_segmentControl.selectedSegmentIndex == 1) {
        [_recordDataSource removeAllObjects];
        _comboxSelectedIndex1 = selectedIndex;
        [self requestForRecordData];

    }

}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    //return [self.dataSource count];
    if (_segmentControl.selectedSegmentIndex == 0) {
        return _schemeDataSource.count;
    }
    else if (_segmentControl.selectedSegmentIndex == 1) {
        return _recordDataSource.count;
//        return 10;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    

    if (_segmentControl.selectedSegmentIndex == 0) {
        
        UITableViewCell *cell = [[UITableViewCell alloc]init];
        static NSString *CellIdentifier1 = @"schemeCell";
        cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
       
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier1];
        }
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; //显示最右边的箭头
        
        //建模填充数据
        ProductListModel * productListModel = _schemeDataSource[indexPath.row];
        
        //cell.textLabel.text = [NSString stringWithFormat:@"%@  解决方案",productListModel.rcm_createtime];guanlifangan_
        [cell.imageView setImage:[UIImage imageNamed:@"guanlifangan_"]];
        cell.textLabel.text = productListModel.solution_name;
        
        return cell;


    } else {
        
        
        static NSString *CellIdentifier2 = @"recordCell";
        
        RecordTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier2];
        
        if (cell == nil) {
            cell = [[RecordTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier2];
        }
        //建模填充数据
         CustomerRecordModel * customerRecordModel = _recordDataSource[indexPath.row];
        [cell fillCellWithModel:customerRecordModel];
        return cell;
    }
  
    
}

#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (_segmentControl.selectedSegmentIndex == 1)
    {
        return 110;
    }
    
    return 44;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (_segmentControl.selectedSegmentIndex == 0) {
        ProgramKindViewController *programKindViewController = [[ProgramKindViewController alloc] init];
        programKindViewController.title = @"解决方案";
        
        ProductListModel * productListModel = _schemeDataSource[indexPath.row];
        programKindViewController.solution_id = productListModel.solution_id;
        
        [self.navigationController pushViewController:programKindViewController animated:NO];

    }
    else if (_segmentControl.selectedSegmentIndex == 1) {
        
    
    }

}








@end
